package controller;
import java.net.URL;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.List;

import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.DurationUpdateEvent;
import javax.media.EndOfMediaEvent;
import javax.media.Manager;
import javax.media.Player;

import model.RadioModel;

// Javadoc http://java.sun.com/javase/technologies/desktop/media/jmf/2.1.1/apidocs/javax/media/ControllerEvent.html

class RadioPlayer {
	
	private List<EventListener> listeners = new ArrayList<EventListener>();

	private Player player;
	
	private RadioModel model;

	public RadioPlayer(RadioModel model) {
		this.model = model;
	}
	
	public void stop() {
		player.stop();
		player.close();
	}
	
	public void play() {
		try {
			Track track = model.getTrack();
			System.out.println("Now playing " + track.getTitle());
			URL url = new URL(track.getLocation());
			
			//mediaLocator = new MediaLocator(url);
			//playMP3 = Manager.createPlayer(mediaLocator);
			player = Manager.createPlayer(url);
			
		} catch (java.io.IOException e) {
			System.out.println(e.getMessage());
		} catch (javax.media.NoPlayerException e) {
			System.out.println(e.getMessage());
		}

		player.addControllerListener(new ControllerListener() {
			public void controllerUpdate(ControllerEvent e) {
				if (e instanceof EndOfMediaEvent) {
					player.stop();
					player.close();
					notifyEndOfMedia();
					
				} else if (e instanceof DurationUpdateEvent) {
					DurationUpdateEvent event = (DurationUpdateEvent) e;
					notifyUpdateDuration(event.getDuration().getNanoseconds());
				}
			}
		});
		player.realize();
		player.start();
	}

	public void run() {
		
	}
	
	public void addListener(EventListener listener) {
		listeners.add(listener);
	}
	
	private void notifyEndOfMedia() {
		for (EventListener listener : listeners) {
			if (listener instanceof RadioPlayerListener) {
				// Eventuell in einem Worker Thread abarbeiten
				((RadioPlayerListener) listener).endOfMedia();
			}
		}
	}
	
	private void notifyUpdateDuration(long nanoseconds) {
		for (EventListener listener : listeners) {
			if (listener instanceof RadioPlayerListener) {
				// Eventuell in einem Worker Thread abarbeiten
				((RadioPlayerListener) listener).durationUpdate(nanoseconds);
			}
		}
	}

	

}
